const glob = require('glob')
const path = require('path')
const fs = require('fs')
const cp = require('child_process')

const files = glob.sync("**/!(_)*.md", {ignore: ["readme.md", "node_modules/**"]})
const tree = {}

files.sort().forEach((p) => {
  // const relativePath = path.relative(baseDir, p);
  // const parts = relativePath.split(path.sep);

  const parts = p.split('/');

  let node = tree;

  parts.forEach((part, index) => {
    if (!node[part]) {
      node[part] = {};
    }

    if (index === parts.length - 1) {
      node[part] = p;
    } else {
      node = node[part];
    }
  });
});

let temp = fs.readFileSync(path.join(__dirname, '_temp.md'), {encoding: "utf-8"}) + '\n'

const readTree = (t, level = "##") => {
  Object.entries(t).forEach(([key, value]) => {
    if(typeof value === 'string') temp += `- [${key}](./${path.relative(process.cwd(), value).replace('\\', '/')})\n\n`
    else {
      temp += level + ' ' + key + '\n\n'
      readTree(value, level + '#')
    }
  })
}

readTree(tree)


fs.writeFileSync(path.join(process.cwd(), 'readme.md'), temp, {encoding: 'utf-8'})

cp.execSync(`git add .`, {cwd: process.cwd()})
